import Vue from 'vue'
import VueRouter from 'vue-router'
import { routerMode } from '../config/env'

// 嵌套路由
import App from '../components/App'

// 中大MBA的实时票选排名H5
const MBAVoteList = r => require.ensure([], () => r(require('../views/activity/zhongda-mba-vote/vote-list/vote-list')), 'vote-list')
const MBAVoteDetail = r => require.ensure([], () => r(require('../views/activity/zhongda-mba-vote/vote-detail/vote-detail')), 'vote-detail')
const MBAVoteSuccess = r => require.ensure([], () => r(require('../views/activity/zhongda-mba-vote/vote-success/vote-success')), 'vote-success')
const MBAVoteLogin = r => require.ensure([], () => r(require('../views/activity/zhongda-mba-vote/vote-login/vote-login')), 'vote-login')
const MBAVoted = r => require.ensure([], () => r(require('../views/activity/zhongda-mba-vote/voted/voted')), 'voted')

const Logout = r => require.ensure([], () => r(require('../views/logout/logout')), 'logout')
const UserAgree = r => require.ensure([], () => r(require('../views/user-agree/user-agree')), 'user-agree')

var routes = [{
  path: '/',
  component: App, // 顶层路由，对应index.html
  children: [ // 二级路由。对应App.vue
    // 地址为空时跳转home页面
    {
      path: '',
      redirect: '/vote-list'
    }, {
      path: '/vote-list',
      component: MBAVoteList
    }, {
      path: '/vote-detail',
      component: MBAVoteList
    }, {
      path: '/vote-success',
      component: MBAVoteList
    }, {
      path: '/voted',
      component: MBAVoteList
    }, {
      path: '/vote-login',
      component: MBAVoteList
    }, {
      path: '/user-agree',
      component: MBAVoteList
    }, {
      path: '/logout',
      component: MBAVoteList
    }
  ]
}]

Vue.use(VueRouter)
const router = new VueRouter({
  routes,
  mode: routerMode,
  strict: process.env.NODE_ENV !== 'production',
  scrollBehavior (to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      if (from.meta.keepAlive) {
        from.meta.savedPosition = document.body.scrollTop
      }
      return {
        x: 0,
        y: to.meta.savedPosition || 0
      }
    }
  }
})

router.beforeEach((to, from, next) => {
  if (to.meta.requireAuth) { // 判断该路由是否需要登录权限
    if (window.localStorage.getItem('voteToken')) { // 通过vuex state获取当前的token是否存在
      next()
    } else {
      next({
        path: '/vote-list',
        query: { redirect: to.fullPath } // 将跳转的路由path作为参数，登录成功后跳转到该路由
      })
    }
  } else {
    next()
  }
})

router.afterEach((to, from, next) => {
  // console.log('PUSH===>>>' + location.pathname + '#' + to.fullPath)
  window._hmt.push(['_setAutoPageview', false])
  window._hmt.push(['_trackPageview', location.pathname + '#' + to.fullPath])
})

export default router
